package com.example.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserListidRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubidRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiUserListidResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubidResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.example.service.UserService;
import com.example.service.serviceImpl.UserServiceImpl;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class DepartUserGet {

    @Autowired
    private UserService userService;

    List<Long> departlist = new ArrayList<>();
    List<String> useridlist = new ArrayList<>();

    @ResponseBody
    @RequestMapping("departIdGet")
    public void departIdGet(HttpServletRequest request){

        //每次更新的时候清空user表，防止出现离职但是数据库里面数据未删除的情况。
        userService.deleteUser();

        HttpSession session = request.getSession();
        String token = session.getAttribute("Token").toString();
        getid(1L,token);
        System.out.println(departlist);
        System.out.println(departlist.size());

        //获取全部员工的uid
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
            OapiUserListidRequest req = new OapiUserListidRequest();
            for (int i=0;i<departlist.size();i++) {
                req.setDeptId(departlist.get(i));
                OapiUserListidResponse rsp = client.execute(req, token);
                JSONObject object = JSONObject.parseObject(rsp.getBody());
                JSONArray jsonArray = object.getJSONObject("result").getJSONArray("userid_list");
                for (int j=0;j<jsonArray.size();j++){
                    String uid = jsonArray.getString(j);
                    useridlist.add(uid);
                }
            }
            //计算重复员工个数。利用键值对插入，把查找的list插入键，当有重复的键的时候就计算一次；
//            int repeat=0;
//            int num=0;
//            Map<Object, Integer> map = new TreeMap<Object, Integer>();
//            for (Object i : useridlist) {
//                if (map.get(i) == null) {
//                    map.put(i, 1);
//                    num++;
//                } else {
//                    map.put(i, map.get(i) + 1);
//                    repeat++;
//                }
//            }
//            System.out.println("总个数是："+useridlist.size()+"\n重复的个数为："+repeat+"\n实际个数是："+(useridlist.size()-repeat));
//            System.out.println("num:"+num);
        } catch (ApiException e) {
            e.printStackTrace();
        }

        //上面获取到了所有人的uid，下面将在钉钉里面找到对应的名字与工号。
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest request1 = new OapiV2UserGetRequest();
            request1.setLanguage("zh_CN");
            int length=useridlist.size();
            //遍历钉钉里面的所有人，找到工号后和数据库里面的工号进行查找，有相同的就更新名字，没有就插入。
            int update =0,insert=0;
            System.out.println(length);
            for (int ul=0;ul<length;ul++) {
                request1.setUserid(useridlist.get(ul));
                OapiV2UserGetResponse rsp1 = client.execute(request1, token);

                JSONObject object2 = JSONObject.parseObject(rsp1.getBody());
                String jobid = object2.getJSONObject("result").getString("job_number");
                //System.out.println("工号："+jobid);
                if (jobid!=null&&!jobid.equals("")) {
                    //System.out.println(jobid);
                    String uname = object2.getJSONObject("result").getString("name");
                    if (userService.hasId(jobid)) {
                        userService.InsertUser(jobid, uname);
                        insert += 1;
                    } else {
                        userService.updateUser(jobid, uname);
                        update += 1;
                    }
                }
                System.out.println("jobid:"+jobid+"   length："+ul+"\n插入了"+insert+"条新数据"+" 更新了"+update+"条旧数据");
                System.out.println();
            }
            System.out.println("全部ok！");
        } catch (ApiException e) {
            System.out.println("1"+e);
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("2"+e);
            e.printStackTrace();
        }
    }

    //递归搜索全部的部门id：当当前的部门下的dept_id数组长度不为空，证明还有子部门，此时重复调用此函数读取子部门的子部门。
    public void getid(long l,String token) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            req.setDeptId(l);
            req.setLanguage("zh_CN");
            OapiV2DepartmentListsubResponse rsp = client.execute(req, token);
            JSONObject object = JSONObject.parseObject(rsp.getBody());
            //名下子部门长度
            int length = object.getJSONArray("result").size();
            for (int i=0;i<length;i++) {
                String deptid = object.getJSONArray("result").getJSONObject(i).getString("dept_id");
                Long dept_id = Long.parseLong(deptid);
                System.out.println(dept_id);
                //把部门id添加到list中
                departlist.add(dept_id);
                //递归调用本函数，探索有没有子部门
                getid(dept_id,token);
            }

        } catch (ApiException e) {
            e.printStackTrace();
        }
    }
}
